package secondriver.heathfood.common;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import secondriver.heathfood.client.Constants;
import secondriver.heathfood.util.LogUtil;

import java.io.IOException;
import java.io.InputStream;

/**
 * Author : secondriver
 * Date :  2015/10/20
 */
public class LoadNetImageTask extends AsyncTask<String, Integer, Bitmap> {

    private static final LogUtil logUtil = LogUtil.getLogger(LoadNetImageTask.class.getName());

    @Override
    protected Bitmap doInBackground(String... params) {
        logUtil.info("doInBackground load net images .");
        if (null != params && params.length >= 1) {
            String imageUrl = params[0];
            InputStream inputStream = null;
            try {
                inputStream = new java.net.URL(imageUrl).openStream();
                BitmapFactory.Options opts = new BitmapFactory.Options();
                opts.inJustDecodeBounds = true;
                BitmapFactory.decodeStream(inputStream, null, opts);
                if (null != inputStream) {
                    inputStream.close();
                }
                int outWidth = opts.outWidth;
                int outHeight = opts.outHeight;
                int width = outWidth;
                int height = outHeight;

                int inSampleSize = 1;

                if (height > Constants.IMAGE_MAX_WIDTH || width > Constants.IMAGE_MAX_HEIGHT) {
                    final int halfHeight = height / 2;
                    final int halfWidth = width / 2;
                    // Calculate the largest inSampleSize value that is a power of 2 and keeps both
                    // height and width larger than the requested height and width.
                    while ((halfHeight / inSampleSize) > Constants.IMAGE_MAX_HEIGHT
                            && (halfWidth / inSampleSize) > Constants.IMAGE_MAX_WIDTH) {
                        inSampleSize *= 2;
                    }
                }
                opts.inSampleSize = inSampleSize;
                opts.inJustDecodeBounds = false;
                inputStream = new java.net.URL(imageUrl).openStream();
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, opts);
                return bitmap;
            } catch (OutOfMemoryError error) {
                logUtil.warn("doInBackground load net images occur OutOfMemoryError.");
            } catch (IOException e) {
                logUtil.error("doInBackground load net images error .", e.getCause());
            } finally {
                if (null != inputStream) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }
}
